package net.tngou.action.api;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser.Operator;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

import net.tngou.action.BaseAction;
import net.tngou.jdbc.QueryHelper;
import net.tngou.lucene.Field;
import net.tngou.lucene.Page;
import net.tngou.lucene.TngouDBHelp;
import net.tngou.lucene.Field.Type;
import net.tngou.pojo.Data_comp;
import net.tngou.pojo.POJO;
import net.tngou.util.DateUtil;
import net.tngou.util.StringUtil;

/**
 * 搜索
 * @author tngou@tngou.net
 *
 */
public class SearchApi extends BaseAction {

	TngouDBHelp tngouDBHelp  = new TngouDBHelp();
	Analyzer analyzer = new SmartChineseAnalyzer();
	@Override
	public void execute() throws ServletException, IOException {
		String tableName="comp";
		String key= request.getParameter("keyword");//关键字
		String type= request.getParameter("type");//企业类型  不填是全部   0-个体 1-企业
		String isscope= request.getParameter("isscope");//是否通过经营范围匹配（默认不匹配，1-匹配）
		String ism= request.getParameter("ism");//有手机号（默认全部 1-有 0-没有）
		String isd= request.getParameter("isd");//有座机号（默认全部 1-有 0-没有）
		String scapi= request.getParameter("scapi");//注册资本范围最小值（默认为0）
		String ecapi= request.getParameter("ecapi");//注册资本范围最大值（默认为最大）
		String sdate= request.getParameter("sdate");//注册时间范围最小值（默认为0000-00-00）
		String edate= request.getParameter("edate");//注册时间范围最大值（默认为9999-99-99）
		String provincecode= request.getParameter("provincecode");//省份编码
		String citycode= request.getParameter("citycode");//城市编码
		String countycode= request.getParameter("countycode");//区(市)县
		String industrycode= request.getParameter("industrycode");//门类编码
		String subindustrycode= request.getParameter("subindustrycode");//大类编码
		
		if(StringUtil.isEmpty(key)
				&&StringUtil.isEmpty(type)
				&&StringUtil.isEmpty(isscope)
				&&StringUtil.isEmpty(ism)
				&&StringUtil.isEmpty(isd)
				&&StringUtil.isEmpty(scapi)
				&&StringUtil.isEmpty(ecapi)
				&&StringUtil.isEmpty(sdate)
				&&StringUtil.isEmpty(edate)
				&&StringUtil.isEmpty(provincecode)
				&&StringUtil.isEmpty(citycode)
				&&StringUtil.isEmpty(countycode)
				&&StringUtil.isEmpty(industrycode)
				&&StringUtil.isEmpty(subindustrycode)
				)
		{
			Page p = tngouDBHelp.select(tableName, ask.getPage(), ask.getRows(),true);
			printJson(toJsonP(p));
			return;
		}
		
		BooleanQuery.Builder  builder=new BooleanQuery.Builder();
		
		if(StringUtil.isNotEmpty(key)) {
			
			if("1".equals(isscope)) {
				String[] mysqlFields = { "Name", "OriginalName","Scope"};
				MultiFieldQueryParser qp=new MultiFieldQueryParser(mysqlFields,analyzer);
				qp.setDefaultOperator(Operator.OR);
				try {
					builder.add(qp.parse(key), Occur.MUST);
				} catch (ParseException e) {			
					e.printStackTrace();
				}
			
			}else
			{
				String[] mysqlFields = { "Name", "OriginalName"};
				MultiFieldQueryParser qp=new MultiFieldQueryParser(mysqlFields,analyzer);
				qp.setDefaultOperator(Operator.OR);
				try {
					builder.add(qp.parse(key), Occur.MUST);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			
			
		}
		if("1".equals(type)||"0".equals(type))
			builder.add(IntPoint.newExactQuery("Type", Integer.parseInt(type)), Occur.MUST);

		if("1".equals(ism)||"0".equals(ism))
			builder.add(IntPoint.newExactQuery("ism", Integer.parseInt(ism)), Occur.MUST);
		if("1".equals(isd)||"0".equals(isd))
			builder.add(IntPoint.newExactQuery("isd", Integer.parseInt(isd)), Occur.MUST);

		
		if(StringUtil.isNotEmpty(provincecode)) 
			builder.add(new TermQuery(new Term("ProvinceCode",provincecode)), Occur.MUST);
		if(StringUtil.isNotEmpty(citycode)) 
			builder.add(new TermQuery(new Term("CityCode",citycode)), Occur.MUST);
		if(StringUtil.isNotEmpty(countycode)) 
			builder.add(new TermQuery(new Term("CountyCode",countycode)), Occur.MUST);
		if(StringUtil.isNotEmpty(industrycode)) 
			builder.add(new TermQuery(new Term("IndustryCode",industrycode)), Occur.MUST);
		if(StringUtil.isNotEmpty(subindustrycode)) 
			builder.add(new TermQuery(new Term("SubIndustryCode",subindustrycode)), Occur.MUST);

			
		if(StringUtil.isNotEmpty(scapi)||StringUtil.isNotEmpty(ecapi))	
		{
			double s=0;
			double e=Double.MAX_VALUE;
			if(StringUtil.isNotEmpty(scapi)&&NumberUtils.isNumber(scapi))
				s=Double.parseDouble(scapi);
			if(StringUtil.isNotEmpty(ecapi)&&NumberUtils.isNumber(ecapi))
				e=Double.parseDouble(ecapi);
			builder.add(DoublePoint.newRangeQuery("Capi", s-1, e+1), Occur.MUST);
		}
		if(StringUtil.isNotEmpty(sdate)||StringUtil.isNotEmpty(edate))	
		{
			long s=0;
			long e=Long.MAX_VALUE;
			LocalDateTime sd = DateUtil.parse(sdate);
			LocalDateTime ed = DateUtil.parse(edate);
			if(sd!=null)s=DateUtil.toSqlDate(sd.toLocalDate().minusDays(1)).getTime();
			if(ed!=null)e=DateUtil.toSqlDate(ed.toLocalDate().plusDays(1)).getTime();
			builder.add(LongPoint.newRangeQuery("sdate", s, e), Occur.MUST);
		}
		
		Query query=builder.build();
	
		Page p = tngouDBHelp.select(tableName, ask.getPage(), ask.getRows(),   query);
		printJson(toJsonP(p));
	}
	
	
}
